package com.eian.boot.rabbit.core.listener;

import com.eian.boot.json.utils.JsonUtils;
import com.eian.boot.rabbit.exception.MessageConversionException;
import com.eian.boot.rabbit.util.TraceIdUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.RabbitListenerErrorHandler;
import org.springframework.stereotype.Component;

@Component
public class MessageListener {

    private static final Logger logger = LoggerFactory.getLogger(MessageListener.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static <T> T extractPayload(Message message, Class<T> payloadType) {
        try {
            String body = new String(message.getBody());
            JsonNode root = objectMapper.readTree(body);

            JsonNode traceIdNode = root.get("traceId");
            if (traceIdNode != null) {
                TraceIdUtil.setTraceId(traceIdNode.asText());
            }

            JsonNode payloadNode = root.get("payload");
            if (payloadNode != null) {
                return JsonUtils.parseObject(payloadNode.toString(), payloadType);
            } else {
                throw new MessageConversionException("消息负载缺失");
            }
        } catch (Exception e) {
            throw new MessageConversionException("消息数据转换失败", e);
        }
    }

    public static RabbitListenerErrorHandler unifiedErrorHandler() {
        return (amqpMessage, channel, springMessage, exception) -> {
            logger.error("消息处理失败 : {}",
                    springMessage != null ? springMessage.getPayload() : "未知的消息体",
                    exception);
            return null;
        };
    }
}